import { Injectable, NotFoundException, Optional, Inject } from '@nestjs/common';

/**
 * 模拟的一些服务
 */
@Injectable()
export class SomeService {
  /**
   * 执行一些异步操作
   * @returns 操作结果
   */
  async doSomething() {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve('异步操作成功完成');
      }, 1000);
    });
  }


  // async doSomething(): Promise<string> {
  //   return new Promise((resolve) => {
  //     setTimeout(() => {
  //       resolve('异步操作成功完成');
  //     }, 1000);
  //   });
  // }
}

// 模拟用户数据
const mockUsers = [
  { id: '1', name: '张三', email: 'zhangsan@example.com', createdAt: new Date('2023-01-01') },
  { id: '2', name: '李四', email: 'lisi@example.com', createdAt: new Date('2023-01-02') },
  { id: '3', name: '王五', email: 'wangwu@example.com', createdAt: new Date('2023-01-03') },
  { id: '4', name: '赵六', email: 'zhaoliu@example.com', createdAt: new Date('2023-01-04') },
  { id: '5', name: '钱七', email: 'qianqi@example.com', createdAt: new Date('2023-01-05') },
];

@Injectable()
export class AppService {
  getHello(): string {
    return 'Hello World!';
  }

  createUser(user: { name: string; email: string }) {
    return {
      id: Math.random().toString(36).substr(2, 9),
      ...user,
      createdAt: new Date(),
    };
  }

  /**
   * 获取用户列表（分页）
   * @param page - 页码（可选，默认值：1）
   * @param limit - 每页数量（可选，默认值：10）
   * @param name - 用户名（可选）
   * @param email - 用户邮箱（可选）
   * @returns 用户列表及分页信息
   */
  getUsers(page: number = 1, limit: number = 10, name?: string, email?: string) {
    let users = mockUsers;

    if (name) {
      const nameRegex = new RegExp(name, 'i');
      users = users.filter(user => nameRegex.test(user.name));
    }

    if (email) {
      const emailRegex = new RegExp(email, 'i');
      users = users.filter(user => emailRegex.test(user.email));
    }

    const startIndex = (page - 1) * limit;
    const endIndex = page * limit;
    const paginatedUsers = users.slice(startIndex, endIndex);

    return {
      data: paginatedUsers,
      total: users.length,
    };
  }

  /**
   * 根据ID获取用户
   * @param id - 用户ID
   * @returns 用户信息
   * @throws NotFoundException 当用户不存在时
   */
  getUserById(id: string) {
    const user = mockUsers.find(user => user.id === id);
    if (!user) {
      throw new NotFoundException(`用户不存在，ID: ${id}`);
    }
    return user;
  }
}

@Injectable()
export class HttpService<T> {
  constructor(@Optional() @Inject('HTTP_OPTIONS') private httpClient: T) {
    // 检查依赖是否存在
    if (this.httpClient) {
      // 有依赖时的逻辑
      console.log('HTTP 客户端已注入', this.httpClient);
    } else {
      // 无依赖时的逻辑（如使用默认实现）
      console.log('使用默认 HTTP 客户端', this.httpClient);
    }
  }

  get(url: string, headers?: Record<string, string>) {

    if (this.httpClient) {
      return this.httpClient['get'](url, headers);
    }


    const options: RequestInit = { headers };
    console.log('Making request to:', url);
    console.log('Request headers:', headers);
    
    return fetch(url, options)
      .then(response => {
        console.log('Response status:', response.status);
        
        // Check if response is successful
        if (!response.ok) {
          // Try to get error details from response body
          return response.text()
            .then(text => {
              try {
                // Attempt to parse as JSON
                const errorData = JSON.parse(text);
                throw new Error(`HTTP error! status: ${response.status}, details: ${JSON.stringify(errorData)}`);
              } catch (jsonError) {
                // If not JSON, use plain text
                throw new Error(`HTTP error! status: ${response.status}, body: ${text}`);
              }
            })
            .catch(textError => {
              throw new Error(`HTTP error! status: ${response.status}, unable to read response body`);
            });
        }
        
        // Try to parse response as JSON first
        return response.text()
          .then(text => {
            try {
              return JSON.parse(text);
            } catch (e) {
              return text;
            }
          });
      })
      .catch(error => {
        console.error('Error in HTTP request:', error.message);
        console.error('Error details:', error);
        throw new Error(`Failed to make HTTP request: ${error.message}`);
      });
  }

}